import axios from 'axios';
import store from '@/store';
import qs from 'qs';
let Base64 = require('js-base64').Base64
    // import cookies from 'vue-cookies'

let options = {
    axios,
    store,
    qs,
    Message: function() {},
};
export function setMessage(Message) {
    options.Message = Message;
}
let timeout = 0;
let maxtimer = 2000;
let headers = {};
let downLoadTimer = true;
timeout = options.timeout || 120 * 1000;
headers = Object.assign({
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-requested-with': 'XMLHttpRequest',
    },
    options.headers
);

const request = options.axios.create({ timeout, headers });
/**@desc 在请求前做的操作**/
request.interceptors.request.use(
    function(config) {
        const parames = getparames()
        let noCache = new Date().getTime();
        let data = config.data || {};
        let token = window.token || data.token || localStorage.getItem('token') || localStorage.getItem('THPMSCookie')
        if (data && data.cxLogName && data.cxLogName.length > 0) {
            let cxLogName = encodeURIComponent(data.cxLogName);
            config.headers['cxLogName'] = cxLogName; //变动的名称
        }

        if (parames.software == 'bs') { // exe产品系统访问，隐藏导航
            store.commit('setData', {
                label: 'software',
                value: 'bs'
            });
        }
        if (token === null || token === 'undefined') {
            token = parames.t || parames.token || data.token
            if (token && token.split('BBSS').length > 1) { // 需要base64解密
                token = decodeURIComponent(Base64.decode(token.split('BBSS')[1]))
            }
            if (token) {
                localStorage.setItem('token', token);
                localStorage.setItem('THPMSCookie', token)
            } else {
                goLogin(data)
            }
        }
        if (token) {
            config.headers['token'] = token
        }
        config.headers['startTimer'] = `${noCache}`; //请求前记录时间

        if (config.method === 'get' || config.method === 'GET') {
            let pms = '';
            Object.keys(data).forEach((v, i) => {
                if (pms === '') {
                    pms = v + '=' + data[v];
                } else {
                    pms += '&' + v + '=' + data[v];
                }
            });
            if (config.url.indexOf('?') === -1 && pms !== '') {
                config.url = config.url + '?' + pms;
            } else if (pms !== '') {
                config.url = config.url + '&' + pms;
            }
        } else if (
            config.headers['Content-Type'].indexOf(
                'application/x-www-form-urlencoded'
            ) > -1
        ) {}
        return config;
    },
    function(error) {
        return Promise.reject(error);
    }
);

function getparames(_u) {
    var url = decodeURIComponent(location.href).split('?')
    var pmsArr = url[1] || ''
    if (_u) {
        url = decodeURIComponent(_u).split('?')
    }
    var _obj = {}
    if (pmsArr && pmsArr.length > 0) {
        pmsArr = pmsArr.split('&')
        for (var i in pmsArr) {
            var o = pmsArr[i].split('=')
            _obj[o[0]] = o[1]
        }
    }

    return _obj
}

export function goLogin(data = {}) {
    let _url = location.href
    _url = encodeURIComponent(_url)
        // window.$cookies.remove('token')
        // window.$cookies.remove('THPMSCookie')
    localStorage.removeItem('token')
    localStorage.removeItem('THPMSCookie')
    let object = data.object // 暂时不启动出参
    if (!object) {
        object = (window.LoginUrl || location.origin) + '/sso/page/login'
    }
    location.href = object + '?returnURL=' + _url
}
/**@desc 在请求后做的操作**/
request.interceptors.response.use(
    /**@desc 对响应数据做点什么**/
    response => {
        let endTimer = Date.parse(new Date());
        let endTotalTimer = endTimer - response.config.headers.startTimer;
        const data = response.data;
        if (Object.prototype.toString.call(data) === '[object Object]') {
            data.endTotalTimer = endTotalTimer;
        }
        if (data.code == 401 || data.code == -1 || (!data.success && data.statusCode == 21000)) {
            goLogin(data)
        } else if (data.code != 200 && data.message) {
            if (data.success || data.statusCode == 200) {} else {
                if (response.config.headers.messageErrorAlert == 1) {
                    //如果请求投里面messageErrorAlert为1说明自己处理错误消息
                    if (downLoadTimer) {
                        downLoadTimer = false;
                        options.Message.error(data.message);
                        setTimeout(() => {
                            downLoadTimer = true;
                        }, maxtimer);
                    }
                } else {
                    if (data.statusCode === 21000) {
                        goLogin(data)
                    }
                }
            }
        }

        return data;
    },
    /**@desc 对请求错误做些什么**/
    error => {
        if (error.response) {
            let status = error.response.status;
            if (error.response.status == 401) {
                goLogin(data)
                    // options.store.dispatch('common/gotoLogin');
            } else if (status == 404 || status == 500 || status == 502) {
                if (error.response.config.headers.messageErrorAlert == 1) {
                    if (downLoadTimer) {
                        downLoadTimer = false;
                        options.Message.error(`该功能当前遇到了一些小麻烦，请稍后再试`);
                        setTimeout(() => {
                            downLoadTimer = true;
                        }, maxtimer);
                    }
                }
            } else {
                try {
                    if (error.response.config.headers.messageErrorAlert == 1) {
                        try {
                            if (downLoadTimer) {
                                downLoadTimer = false;
                                options.Message.error(error.response.data);
                                setTimeout(() => {
                                    downLoadTimer = true;
                                }, maxtimer);
                            }
                        } catch (error) {}
                    }
                } catch (error) {}
            }
            return Promise.reject({});
        } else {
            return error;
        }
    }
);
/**@desc 把请求对象**/
export const $api = request;
/**@desc get请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $get = function(url, data = {}, show = false) {
    let [headers, method] = [{}, 'get'];
    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    if (show == false) headers.messageErrorAlert = 1;
    let transformRequest = [data => options.qs.stringify(data)];
    return new Promise(resolve => {
        request({ url, method, data, headers, transformRequest })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc post  表单提交请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $post = function(url, data = {}, show = false, headers = {}) {
    let [method] = ['post'];
    if (show == false) headers.messageErrorAlert = 1;

    let transformRequest = [data => qs.stringify(data)];
    return new Promise(resolve => {
        request({ url, method, data, headers, transformRequest })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc post json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $postJson = function(url, data = {}, show = false) {
    let [headers, method] = [{}, 'post'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'application/json;charset=utf-8';
    headers['token'] = window.token || data.token || localStorage.getItem('token') || localStorage.getItem('THPMSCookie')
    return new Promise(resolve => {
        request({ url, method, data, headers })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc post json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $reqAll = function(url, data = {}, show = false, reqType = 'get', contentType = 'application/json;charset=utf-8') {
    let [headers, method] = [{}, reqType];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = contentType;
    return new Promise(resolve => {
        request({ url, method, data, headers })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc post json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $getJson = function(url, data = {}, show = false) {
    let [headers, method] = [{}, 'get'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'application/json;charset=utf-8';
    return new Promise(resolve => {
        request({ url, method, data, headers })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc post json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $postJsonCode = function(url, data = {}, show = false) {
    let [headers, method] = [{}, 'post'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'application/json;charset=utf-8';
    headers['Accept'] = '*/*';
    headers['Jenkins-Crumb'] =
        '98c7a908add174b58deac6b07de8961e0271bfeddffe189e08bccdb78df2cd78';
    let transformRequest = [data => qs.stringify(data)];
    return new Promise(resolve => {
        request({ url, method, data, headers, transformRequest })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
/**@desc put json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param headers {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $put = function(url, data = {}, show = false, headers) {
    headers = headers || {};
    let [method] = ['put'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'application/json';
    return new Promise(resolve => {
        request({ url, method, data, headers })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};

/**@desc delete json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $delete = function(url, data = {}, show = false, header) {
    let [headers, method] = [header || {}, 'delete'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    return new Promise(resolve => {
        request({ url, method, data, headers })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};

/**@desc post json请求快捷方式
 * @param url {String} 请求url地址
 * @param data {Object} 请求参数
 * @param show {Boolean} 该请求是否使用默认弹框**/
export const $upload = function(
    url,
    data = {},
    onUploadProgress,
    show = false
) {
    let [headers, method] = [{}, 'post'];
    if (show == false) headers.messageErrorAlert = 1;
    headers['Content-Type'] = 'multipart/form-data';
    return new Promise(resolve => {
        request({ url, method, data, headers, onUploadProgress })
            .then(res => resolve(res))
            .catch(error => resolve(error));
    });
};
